package net.sf.rose.business.action.define;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import json.ComboboxBean;
import json.JsonHttpRequestBean;
import json.JsonHttpResponse;
import json.JsonTreeBean;
import net.sf.rose.business.action.Download;
import net.sf.rose.business.bean.base.DownloadFileBean;
import net.sf.rose.business.bean.database.DataTypeMetaBean;
import net.sf.rose.business.bean.database.DataTypeMetaBeans;
import net.sf.rose.business.service.DBMetaService;
import net.sf.rose.exception.SystemErrorCode;
import net.sf.rose.exception.SystemException;
import net.sf.rose.jdbc.DBUtils;
import net.sf.rose.jdbc.UserBean;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.web.OnlineUserListener;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * 功能：
 * 
 * @author fengjian
 * @since 2014/01/29
 */
@Controller
@RequestMapping("/define/dbmeta")
public class DBMetaController {

	/**
	 * 普通查询
	 */
	@RequestMapping("/tree.html")
	public void tree(HttpServletRequest request, HttpServletResponse response, Service service) {
		Map<String, DataTypeMetaBeans> bean = DBMetaService.getAll();
		List<JsonTreeBean> list = new ArrayList<JsonTreeBean>();
		JsonTreeBean tree = new JsonTreeBean();
		tree.setId("all");
		tree.setName("所有数据库");
		tree.setExpanded(true);
		list.add(tree);
		for(String name : bean.keySet()){
			tree = new JsonTreeBean();
			tree.setId(name);
			tree.setName(name);
			tree.setPid("all");
			list.add(tree);
		}
		JsonHttpResponse.renderJson(response, list);
	}

	/**
	 * 返回某个数据库的定义
	 */
	@RequestMapping("/get.html")
	public ModelAndView get(HttpServletRequest request, HttpServletResponse response, String name) {
		if (name == null) {
			return null;
		}
		DataTypeMetaBeans bean = DBMetaService.getAll().get(name);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("data", bean.getDataMetas());
		JsonHttpResponse.renderJson(response, map);
		return null;
	}

	/**
	 * 返回当前使用的数据库的所有数据类型名称
	 */
	@RequestMapping("/getDataType.html")
	public ModelAndView getDataType(HttpServletRequest request, HttpServletResponse response) {
		DataTypeMetaBeans bean = DBMetaService.getService().getUsedDataTypeMetaBeans();
		List<ComboboxBean> list = new ArrayList<ComboboxBean>();
		for (DataTypeMetaBean type : bean.getDataMetas()) {
			ComboboxBean c = new ComboboxBean();
			c.setId(type.getName());
			c.setText(type.getName());
			list.add(c);
		}
		JsonHttpResponse.renderJson(response, list);
		return null;
	}

	/**
	 * 保存数据库字段操作
	 */
	@RequestMapping("/save.html")
	public void save(HttpServletRequest request, HttpServletResponse response, String databaseName, String data) {
		JsonHttpRequestBean json = new JsonHttpRequestBean(data);
		json.parseJson(DataTypeMetaBean.class);
		DataTypeMetaBeans metas = DBMetaService.getAll().get(databaseName);
		int type = 0;
		for (int i = 0; i < json.size(); i++) {
			type = json.getAction(i);
			if (type == DBUtils.TYPE_INSERT_INT) {
				metas.addDataMetaBean((DataTypeMetaBean) json.getBean(i));
			} else if (type == DBUtils.TYPE_UPDATE_INT) {
				metas.updateDataMetaBean((DataTypeMetaBean) json.getBean(i));
			} else if (type == DBUtils.TYPE_DELETE_INT) {
				metas.removeDataMetaBean(((DataTypeMetaBean) json.getBean(i)).getName());
			}
		}
	}

	/**
	 * 添加数据库的定义
	 */
	@RequestMapping("/addDatabase.html")
	public void addDatabase(HttpServletRequest request, HttpServletResponse response, String name) {
		if (name == null) {
			return;
		}
		DataTypeMetaBeans bean = new DataTypeMetaBeans();
		bean.setName(name);
		DBMetaService.getAll().put(name, bean);
		JsonHttpResponse.renderMessage(response, "ok");
	}

	/**
	 * 删除数据库的定义
	 */
	@RequestMapping("/deleteDatabase.html")
	public void deleteDatabase(HttpServletRequest request, HttpServletResponse response, String name) {
		DBMetaService.getAll().remove(name);
		JsonHttpResponse.renderMessage(response, "ok");
	}

	/**
	 * 保存数据库定义
	 */
	@RequestMapping("/saveDatabase.html")
	public void saveDatabase(HttpServletRequest request, HttpServletResponse response) {
		UserBean user = OnlineUserListener.getOnlineUser(request);
		if (user == null) {
			user = new UserBean();
			user.setUserName("system");
		}
		DBMetaService.save(user);
		JsonHttpResponse.renderMessage(response, "保存成功！");
	}

	/**
	 * 提交操作
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/input.html")
	public ModelAndView input(HttpServletRequest request) {
		Object obj = request.getSession().getAttribute(Download.TEMP_FILES);
		if (obj == null) {
			throw new SystemException("Session中找不到上传的文件。", SystemErrorCode.A_PRARAMTER_LOST_ERROR);
		}
		Map<String, DownloadFileBean> map = (Map<String, DownloadFileBean>) obj;
		InputStream in = null;
		try {
			for (DownloadFileBean bean : map.values()) {
				if (bean.getData() != null) {
					in = bean.getData().getInputStream();
				}
			}
		} catch (IOException e) {
			throw new SystemException("上传的文件读取错误 !", SystemErrorCode.A_PRARAMTER_LOST_ERROR);
		}
		if (in == null) {
			throw new SystemException("没有找到上传的文件 !", SystemErrorCode.A_PRARAMTER_LOST_ERROR);
		}
		DBMetaService.input(in);
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "导入成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/output.html")
	public String output(HttpServletRequest request) {
		File file = DBMetaService.output();
		request.setAttribute(Download.DOWNLOAD_FILE, file);
		request.setAttribute(Download.DOWNLOAD_FILE_NAME, "数据库元数据配置.xml");
		return "forward:/download.html";
	}
}
